package com.c2b.algorithm.leetcode.lcr;

/**
 * <a href="https://leetcode.cn/problems/remove-nth-node-from-end-of-list/">删除链表的倒数第 N 个结点(Remove Nth Node From End of List)</a>
 * <p>给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。 </p>
 * <p>
 * <b>示例</b>
 * <pre>
 * 示例 1：
 *      输入：head = [1,2,3,4,5], n = 2
 *      输出：[1,2,3,5]
 *
 * 示例 2：
 *      输入：head = [1], n = 1
 *      输出：[]
 *
 * 示例 3：
 *      输入：head = [1,2], n = 1
 *      输出：[1]
 * </pre>
 * </p>
 * <p>
 * <b>提示：</b>
 *     <ul>
 *          <li>链表中结点的数目为 sz</li>
 *          <li>1 <= sz <= 30</li>
 *          <li>0 <= Node.val <= 100</li>
 *          <li>1 <= n <= sz</li>
 *     </ul>
 * </p>
 *
 * @author c2b
 * @since 2024/3/19 11:36
 */
public class LCR021 {
    static class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            if (head == null) {
                return null;
            }
            ListNode dummyHead = new ListNode(-1, head);
            ListNode fast = dummyHead;
            for (int i = 0; i < n; i++) {
                if (fast == null) {
                    return null;
                }
                fast = fast.next;
            }
            ListNode slow = dummyHead;
            while (fast.next != null) {
                fast = fast.next;
                slow = slow.next;
            }
            slow.next = slow.next.next;
            return dummyHead.next;
        }
    }
}
